#include "bsp_can.h"

extern CAN_HandleTypeDef hcan1; // can1句柄

uint8_t can_receive_data[8];

void can_filter_init() // 初始化过滤器
{
  CAN_FilterTypeDef can_filter_st;
  can_filter_st.FilterActivation = ENABLE;
  can_filter_st.FilterMode = CAN_FILTERMODE_IDMASK;
  can_filter_st.FilterScale = CAN_FILTERSCALE_32BIT;
  can_filter_st.FilterIdHigh = 0x0000;
  can_filter_st.FilterIdLow = 0x0000;
  can_filter_st.FilterMaskIdHigh = 0x0000;
  can_filter_st.FilterMaskIdLow = 0x0000;
  can_filter_st.FilterBank = 0;
  can_filter_st.FilterFIFOAssignment = CAN_RX_FIFO0;
  HAL_CAN_Start(&hcan1);
  HAL_CAN_ConfigFilter(&hcan1, &can_filter_st);
  HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING); // 激活接收口FIFO0中断
}

void can_transmit(int motor1,int motor2,int motor3,int motor4)//发送函数
{
  CAN_TxHeaderTypeDef can_tx_message;
	uint32_t send_mail_box;
  uint8_t can_send_data[8] = {0};//发送的数据帧

	can_tx_message.StdId = 0x200;//ID
	can_tx_message.IDE = CAN_ID_STD;
	can_tx_message.RTR = CAN_RTR_DATA;
	can_tx_message.DLC = 0x08;
 
	can_send_data[0] = motor1 >> 8;
	can_send_data[1] = motor1;
	can_send_data[2] = motor2 >> 8;
	can_send_data[3] = motor2;
	can_send_data[4] = motor3 >> 8;
	can_send_data[5] = motor3;
	can_send_data[6] = motor4 >> 8;
	can_send_data[7] = motor4;
 
	HAL_CAN_AddTxMessage(&hcan1,&can_tx_message,can_send_data,&send_mail_box);
}

//接收中断
/*CAN接收中断函数*/
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *CanNum)
{
	CAN_RxHeaderTypeDef can_rx_message;

  HAL_CAN_GetRxMessage(&hcan1, CAN_FILTER_FIFO0, &can_rx_message, can_receive_data); // 从FIFO0中读出数据
}

void deal_motor_message(uint8_t *rx_data, Motor_Message *motor)
{
  motor->encode = (uint16_t)((can_receive_data[0] << 8) | can_receive_data[1]);
  motor->angle = motor->encode / 8192.0 * 360.0;

  motor->speed = (int)((can_receive_data[2] << 8) | can_receive_data[3]);
  if (motor->speed > 30000){//反向速度化负
      motor->speed -= 65535;
    }

  motor->current = (int)((can_receive_data[4] << 8) | can_receive_data[5]);
  if (motor->current > 30000){//反向速度化负
      motor->current -= 65535;
    }

  motor->temp = can_receive_data[6];

}


